package cn.bytest.netty.handler;

import cn.bytest.netty.NettyChannel;
import cn.bytets.rpc.api.Channel;
import cn.bytets.rpc.api.headler.AbstractChannelHandler;
import cn.bytets.rpc.api.headler.ChannelHandler;
import cn.bytets.rpc.api.message.ChannelEventRunnable;
import cn.bytets.rpc.api.message.ChannelState;
import cn.bytets.rpc.api.message.Response;
import cn.bytets.rpc.api.message.Result;
import cn.bytets.rpc.common.utils.StringUtils;

/**
 * Netty处理器
 */
public class NettyChannelHandler extends AbstractChannelHandler {

    private ChannelHandler handler;

    public NettyChannelHandler(){}

    public NettyChannelHandler(ChannelHandler handler){
        this.handler = handler;
    }
    /**
     * on channel connected.
     * 这里可以添加读写超时定时任务
     * @param channel channel.
     */
    @Override
    public void connected(Channel channel) {

    }

    /**
     * on channel disconnected.
     * 这里可以取消超时定时任务
     * @param channel channel.
     */
    @Override
    public void disconnected(Channel channel) {

    }

    /**
     * 接收数据
     *
     * @param channel channel.
     * @param message message.
     */
    @Override
    public void received(Channel channel, Object message) {
        if (channel instanceof NettyChannel){
            getExecutorService().execute(new ChannelEventRunnable(this,channel, ChannelState.RECEIVED,message));
        }
    }

    /**
     * on exception caught.
     * 异常
     * @param channel   channel.
     * @param exception exception.
     */
    @Override
    public void caught(Channel channel, Throwable exception) {
        Response response = new Response();
        response.setErrorMessage(StringUtils.toString(exception));
        response.setId(channel.getRequest().getId());
        response.setStatus(Response.SERVER_ERROR);
        getExecutorService().execute(new ChannelEventRunnable(this,channel,ChannelState.CAUGHT,response,exception));
    }
}
